package com.my.aslife.utils;

import com.my.aslife.module.common.Constant;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class Encryption {

    private Encryption() {}

    public static String getBash64AndMD5(String str) throws Exception {
        str = Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
        return getCommentEncryption(str);
    }

    public static String getMD5(String str) throws Exception {
        return getCommentEncryption(str);
    }

    private static String getCommentEncryption(String str) throws Exception {
        str = str + Constant.KEY;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            String value = new BigInteger(1, md.digest()).toString(16);
            return value;
        } catch (Exception e) {
            throw new Exception("MD5加密出现错误");
        }
    }
}